#include "mouse.h"
Mouse::Mouse(){
    this->x=0;
    this->y=0;
    this->dpi_=0;
    this->lock_=false;
    this->xbuf_=this->ybuf_=0;
    this->xtot=this->ytot=0;
    memset(this->mdata, sizeof(this->mdata),'\0');
}
Mouse::~Mouse(){
    delete this->logger;
}
void  Mouse::run(){
    this->ident=*((int *)arg);

    snprintf(this->mouse,sizeof(this->mouse),"/dev/input/mouse%d",this->ident);
    char temp[10];
    snprintf(temp,sizeof(temp),"mouse%d",this->ident);
    logger = new Log(temp);
    this->readm(mouse);
}
void  Mouse::readm(string mouse){
    pipe.open(mouse.c_str(),ios::in | ios::binary);
    if(pipe.is_open()){
        while (pipe.read(mdata,3)){
            this->handleData();
            //this->printDataInfo();
            memset(this->mdata, sizeof(this->mdata),'\0');
        }
        logger->stuur("EOF bereikt");
        pipe.close();
    }
    else{
        logger->stuur(1,"Can't open mouse device, maybe use sudo? Terminating");
        perror("Kan muis niet opendoen: ");
        exit(-1);
    }
}
void  Mouse::handleData(){
    if(128 & mdata[0] && 1)
        cout << "y-over" << endl;
    if(64 & mdata[0] && 1)
        cout << "x-over" << endl;
    /*
    if(32 & mdata[0] && 1)
        cout << "down" << endl;
    if(16 & mdata[0] && 1)
        cout << "left" << endl;
    if(8 & mdata[0] && 1)
        cout << "always 1" << endl;
    */
    /*
    if(4 & mdata[0] && 1)
        cout << "middle" << endl;
    if(2 & mdata[0] && 1)
        cout << "right" << endl;
    if(1 & mdata[0] && 1)
        cout << "left" << endl;
    */
    if(this->lock_){
        this->xbuf_+=mdata[1];
        this->ybuf_+=mdata[2];
    }
    else{
        this->x+=mdata[1];
        this->y+=mdata[2];
    }
#ifdef CALIB
    this->xtot+=mdata[1];
    this->ytot+=mdata[2];
    cout <<"xtot: "<<this->xtot<<", ytot: "<<this->ytot<<endl;
#endif
}
void  Mouse::setX(int offset){
    this->x=offset;
}
void  Mouse::setY(int offset){
    this->y=offset;
}
int   Mouse::getX(void){
    return this->dpi_*this->x;
}
int   Mouse::getY(void){
    return this->dpi_*this->y;
}
void  Mouse::setDPI(int dpi){
    this->dpi_=dpi;
}
void  Mouse::printDataInfo(){
    printf("%d) ",this->ident);
    for(short i=0; i< BUFSIZE; i++)
        printf("%s %4d, ",this->char2bin(mdata[i]),mdata[i]);
    cout << endl;
}
char* Mouse::char2bin(char in){
	int chPos=BYTE-1;
	static char out[BYTE];
	memset(out, sizeof(out),'\0');
	for (int i = 1; i < 255; i *= 2){
		if (in & i)
			out[chPos] = '1';
		else
			out[chPos] = '0';
		chPos--;
	}
	return out;
}
void Mouse::lock(){
    this->lock_=true;
}
void Mouse::unlock(){
    this->x = this->xbuf_;
    this->y = this->ybuf_;
    this->lock_=false;
    this->xbuf_=0;
    this->ybuf_=0;
}
void Mouse::reset(){
    this->x=0;
    this->y=0;
}
